<template>
    <div class="content">
      <div class="content-head">
        <el-form :inline="true" size="mini" label-position="left">
          <el-form-item label="车间" label-width="50px" class="form-item">
            <el-select v-model="workShop" size="small" placeholder="请选择车间">
                <el-option label="装配线" value="装配线"></el-option>
                <el-option label="机加工" value="机加工"></el-option>
                <el-option label="走心机" value="走心机"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="resetEvent">重置</el-button>
            <el-button type="success" size="mini" icon="el-icon-search" @click="searchEvent">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" icon="el-icon-download" :loading="exportBtnLoading" @click="exportEvent">导出</el-button>
            <el-button type="primary" size="mini" icon="el-icon-document" :loading="saveBtnLoading" @click="saveEvent">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content-table">
        <div class="table-main">
          <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :max-height="tableMaxHeight" row-key="key" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-expand-all="true" class="content-table-item">
            <el-table-column prop="productName" label="物料名称" width="140"></el-table-column>
            <el-table-column prop="productCode" label="物料编码" width="100"></el-table-column>         
            <el-table-column prop="process" label="工艺" width="100"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100"></el-table-column>
            <el-table-column prop="internalStockQuantity" label="厂内库存" width="80"></el-table-column>
            <el-table-column prop="internalMakingStockQuantity" label="厂内在制" width="80"></el-table-column>
            <el-table-column prop="manufacturerMakingStockQuantity" label="厂商在制" width="80"></el-table-column>
            <el-table-column prop="name" label=""  width="100"></el-table-column>
            <el-table-column prop="" label="排产情况" align="center" width="">
              <el-table-column v-for="item,index in scheduleTableHead" :label="item.label" :key="index" align="center" width="120">
                <template slot-scope="{ row, $index }" v-if="item.prop">
                  <el-input v-if="row.name && (row.name === '计划交货')" v-model="row[item.prop]" size="mini" @input="scheduleInputEvent(row,$index,item.label)" placeholder="请输入"></el-input>
                  <span v-if="row.name && (row.name === '厂内需求' || row.name === '累计差异' || row.name === '实际交货')">{{ row[item.prop] }}</span>
                </template>
              </el-table-column>
            </el-table-column> 
          </el-table>
        </div>
      </div>
      <div class="content-footer">
        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100,200]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
      </div>
    </div>
  </template>
  
  <script>
  import { reqMaterialList,reqSaveOrUpdateAll,reqDelSchedules,reqMaterialExport } from "@/api/materialTable.js";
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  export default {
    name:"materailTable",  //物料表
    data() {
      return {
        tableData:[],
        scheduleTableHead:[],  //表头排产情况
        currentPage:1,
        pageSize:10,
        total:0,
        tableLoading:false,
        exportBtnLoading:false,
        tableMaxHeight:450,
        saveBtnLoading:false,
        workShop:"装配线"
      }
    },
    mounted(){
      this.getMaterialList();
      //精致环境下进行自动旋转
      //autoOrientation();
      document.title = "物料表";
      this.calculateTableMaxHeight();
      window.addEventListener('resize',this.calculateTableMaxHeight);
    },
    beforeDestroy(){
      window.removeEventListener('resize',this.calculateTableMaxHeight);
    },
    methods:{
      //分页获取物料列表数据
      async getMaterialList () {
        this.tableLoading = true;
        const parameter = {page:this.currentPage,size:this.pageSize,workShop:this.workShop};
        reqMaterialList(parameter).then(res => {
          this.addSchedulingDateTableHead(res.data.data.content[0]?.materialScheduleTimeRelationList[0]?.scheduleTime);
          if(res.data.code === 200){
            let tmp = null;
            const list = ['厂内需求','计划交货','实际交货','累计差异'];
            this.total = res.data.data.totalElements;
            const dataList = res.data.data.content;
            let parentId = 1;
            tmp = dataList.map(v => {
              const child = new Array();
              let childId = 1;
              for(let i = 0; i < list.length; i ++){
                const childItem = {key:parentId + ':' + String(childId ++),name:list[i]};
                for(let j = 0; j < v.materialScheduleTimeRelationList.length; j ++){
                  let value = null;
                  if(list[i] === '厂内需求'){
                    value = v.materialScheduleTimeRelationList[j].scheduleQuantity || 0;
                  } else if (list[i] === '计划交货'){
                    value = v.materialScheduleTimeRelationList[j].plannedDeliveryQuantity || "";
                  } else if (list[i] === '实际交货'){
                    value = v.materialScheduleTimeRelationList[j].actualDeliveryQuantity || 0;
                  } else if (list[i] === '累计差异'){
                    value = v.materialScheduleTimeRelationList[j].totalDifference || 0;
                  }
                  childItem[v.materialScheduleTimeRelationList[j].scheduleTime] = value;
                }
                child.push(childItem);
              }
              return {
                ...v,key:parentId++,children:child
              }
            })
            this.tableData = tmp;
          }
          this.tableLoading = false;
          console.log("分页获取物料列表信息",res);
        }).catch(err => {
          console.log('分页获取物料列表数据',err);
          this.$message({type:"error",message:"列表数据获取失败"});
          this.tableLoading = false;
        })
      },
      exportEvent() {
        this.$confirm(`即将导出${this.workShop}车间所有数据内容`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}).then(() => {
          this.materialTableExport();
        })
      },
      saveEvent(){
        this.$confirm('保存物料信息, 是否继续?', '提示', { confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {
          this.saveOrUpdateMaterialTable();
        })
      },
      //分页器
      handleCurrentChange(curPage){
        this.currentPage = curPage;
        //重新获取数据
        this.getMaterialList();
      },
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        //重新获取数据
        this.getMaterialList();
      },
      calculateTableMaxHeight(){
        const dom = document.querySelector(".table-main");
        this.$nextTick(() => {
          this.tableMaxHeight = dom.offsetHeight - 10;
        })
      },
      addSchedulingDateTableHead(parameter){
        if(!parameter){
          const workShops = ['装配线','机加工','走心机'];
          const requestList = new Array();
          workShops.forEach(item => {
            const parameter = {page:1,size:1,workShop:item};
            requestList.push(reqMaterialList(parameter));
          })
          Promise.all(requestList).then(response => {
            const tmp = response.map(e => e.data?.data?.content).find(i => i.length > 0);
            if(tmp !== undefined){
              const date = tmp[0]?.materialScheduleTimeRelationList[0]?.scheduleTime;
              this.addSchedulingDateTableHead(date);
            }
          })
          return;
        }
        this.scheduleTableHead = [];
        const tmp = parameter;
        const date = new Date(tmp);
        const y = date.getFullYear();
        const m = date.getMonth() + 1;
        const days = new Date(y,m,0).getDate();
        for(let i = 1; i <= days; i ++){
          const label = y + '-' + (m > 9 ? m : '0' + m) + '-' + (i > 9 ? i : '0'+i);
          const prop = y + '-' + (m > 9 ? m : '0' + m) + '-' + (i > 9 ? i : '0'+i);
          this.scheduleTableHead.push({label:label,prop:prop});
        }
        let addNextMonth = Number(m) + 1 > 12 ? 1 : Number(m) + 1;
        addNextMonth > 9 ? null : '0' + addNextMonth;
        let year = y;
        if(Number(m) >= 12){
          year ++;
        }
        this.scheduleTableHead.push({label:year + '-' + addNextMonth,prop:""});
      },
      scheduleInputEvent(row,index,date){
        console.log('----------------',row,index,date);
        const inputValue = row[date];
        const regex = /^(?!00)\d+(\.\d{0,1})?$/;
        if (!regex.test(inputValue) && inputValue !== '') {
          row[date] = inputValue.slice(0, -1);
        }
        const list = this.tableData;
        const [parentId,childId] = row.key.split(":");
        const e = list.find(v => v.key == parentId);
        const c = e.children;
        for(let i = 0;i < c.length;i ++){
          const v = c[i][date];
          console.log('v',v);
        }
      },
      saveOrUpdateMaterialTable(){
        const list = this.tableData;
        const tmp = list.map(v => {
          const child = v.children;
          v.materialScheduleTimeRelationList.forEach((item,index) => {
            for(let i = 0; i < child.length; i ++){
              if(child[i].name == '厂内需求'){
                item.internalDemand = child[i][item.scheduleTime];
              }
              if(child[i].name == '计划交货'){
                item.plannedDeliveryQuantity = child[i][item.scheduleTime];
              }
              if(child[i].name == '实际交货'){
                item.actualDeliveryQuantity = child[i][item.scheduleTime];
              }
              if(child[i].name == '累计差异'){
                item.totalDifference = child[i][item.scheduleTime];
              }
            }
          })
          return v;
        })
        this.saveBtnLoading = true;
        reqSaveOrUpdateAll(tmp).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"保存成功"});
          }
          console.log('物料表保存或更新',response);
          this.saveBtnLoading = false;
        }).catch(error => {
          this.$message({type:"error",message:"保存失败"});
          console.log('物料表保存或更新',error);
          this.saveBtnLoading = false;
        })
      },
      async materialTableExport(){
        try {
          this.exportBtnLoading = true;
          const res = await reqMaterialExport(this.workShop);
          console.log('物料表导出api',res);
          if (res.status === 200) {
            let blob = res.data;
            let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
            const aLink = document.createElement('a');
            aLink.href = url;
            let timestamp = new Date().getTime();
            aLink.setAttribute('download','物料表_' + timestamp);
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
            this.$message.success('导出成功');
          } else {
            this.$message.error('导出失败,请重试');
          }
          this.exportBtnLoading = false;
        } catch (error){
          const _this = this;
          console.log('物料表导出',error);
          if(error.response.data instanceof Blob){
            //处理响应blob数据的异常信息
            const fileReader = new FileReader();
            fileReader.readAsText(new Blob([error.response.data],{type:'application/octet-stream'}),'utf-8');
            fileReader.onload = () => {
              _this.$message.error('导出失败：' + JSON.parse(fileReader.result).message);
            }
          }
          this.exportBtnLoading = false;
        }
      },
      deletelSchedulesTable(idList){
        return new Promise((resolve,reject) => {
          reqDelSchedules({ids:idList.join(",")}).then(response => {
            if(response.data.code === 200){
              resolve();
            }
            console.log('批量删除物料表数据',response);
          }).catch(error => {
            reject(error);
            console.log('批量删除物料表数据',error);
          })
        })
      },
      resetEvent(){
        this.workShop = "装配线";
        this.getMaterialList();
      },
      searchEvent(){
        const workShop = this.workShop;
        if(workShop !== ""){
          this.getMaterialList();
        }
      },
      //格式化时间
      formatDate(val,type){
        let date = new Date(val);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        if(type === 0){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 1){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day);
        } else if (type === 2){
            return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 3){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
        } else if (type === 4){
          return year + "年" + this.addZero(month) + "月" + this.addZero(day) + "日";
        }
      },
      addZero(val){
        return val > 9 ? val : "0" + val;
      }
    }
  }
  </script>
  
  <style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 1% 2%;
    box-sizing: border-box;
  
    .content-head{
      flex: 0.5;
      .form-item{
        margin-right: 2vw;
      }
    }
    .content-table{
      flex: 9;
      margin: 10px 0;
      .table-date{
        width: 100%;
        height: 2%;
        min-height: 15px;
        margin-bottom: 0.5%;
        display: flex;
        justify-content: right;
      }
      .table-main{
        width: 100%;
        height: 98%;
      }
    }
    .content-footer{
      flex: 0.5;
      display: flex;
      justify-content: flex-end;
    }
  }
  ::v-deep .el-table__header th {
    padding: 0; /* 调整上下内边距 */
  }
  ::v-deep .el-table__row {
    margin-bottom: 15px; /* 调整这个值来改变行间距 */
  }
  ::v-deep .el-table .el-table__cell{
    padding: 0;
  }
  ::v-deep .el-input--mini .el-input__inner {
    height: 22px;
  }
  </style>